#include "touch.h"
#include <stdio.h>
#include <unistd.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

void yige_dian(diao * touch_s)
{
    int fd_touch = open("/dev/input/event0",O_RDWR);
    if(fd_touch == -1)
    {
        perror("fd_touch error");
        return ;
    }
    touch_s->touch_diao_x = -1;
    touch_s->touch_diao_y = -1; 
    struct input_event ev;
    while(1)
    {
        int red = read(fd_touch,&ev,sizeof(ev));
        if(red == -1)
        {
            perror("touch read error");
            close(fd_touch);
            return ;
        }
        if(red != sizeof(ev))
        {
            continue;
        }
        if(ev.type == EV_ABS && ev.code == ABS_X)
        {
            touch_s->touch_diao_x = ev.value;
        }
        if(ev.type == EV_ABS && ev.code == ABS_Y)
        {
            touch_s->touch_diao_y = ev.value;
        }
        if(touch_s->touch_diao_x != -1 && touch_s->touch_diao_y != -1)
        {
            break;
        }
    }
    close(fd_touch);
    return;
}

int pudaun_fx()
{
    int fd_touch = open("/dev/input/event0",O_RDWR);
    if(fd_touch == -1)
    {
        perror("fd_touch error");
        return -1;
    }
    diao *  s = malloc(sizeof(*s));
    diao *  p = malloc(sizeof(*p));
    s->touch_diao_x = -1;
    s->touch_diao_y = -1;
    struct input_event ev;
    while(1)
    {
        int red = read(fd_touch,&ev,sizeof(ev));
        if(red == -1)
        {
            perror("touch read error");
            close(fd_touch);
            return -1;
        }
        if(red != sizeof(ev))
        {
            continue;
        }
        if(ev.type == EV_ABS && ev.code == ABS_X)
        {
            if(s->touch_diao_x == -1)
            {
                s->touch_diao_x = ev.value;
            }
            p->touch_diao_x = ev.value;
        }
        if(ev.type == EV_ABS && ev.code == ABS_Y)
        {
            if(s->touch_diao_y == -1)
            {
                s->touch_diao_y = ev.value;
            }
            p->touch_diao_y = ev.value;
        }
        if((s->touch_diao_x>=0&&s->touch_diao_y>=0&&ev.type == EV_ABS && ev.code == ABS_PRESSURE &&ev.value == 0) || (ev.type == EV_KEY && ev.code == BTN_TOUCH && ev.value == 0))
        {
            break;
        }
    }
    int fx;
    int dis_x=abs(s->touch_diao_x - p->touch_diao_x);
    int dis_y=abs(s->touch_diao_y - p->touch_diao_y);
    if(dis_x>=dis_y)
    {
        if(s->touch_diao_x >= p->touch_diao_x)
        {
            fx = 1;//左滑
        }
        else
        {
            fx = 2;//右滑
        }
    }
    else
    {
        if(s->touch_diao_y >= p->touch_diao_y)
        {
            fx = 3;//上滑
        }
        else
        {
            fx = 4;//下滑
        }
    }
    close(fd_touch);
    free(s);
    free(p);
    return fx;
}
